package wasweisichquiz;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane; // Infobox erstellen
import javax.swing.filechooser.FileFilter;
/**
 * @version Revision 06 - MAIN Changes 
 * + Files werden aus Ordner ausgelesen
 * + Dropdown Box vor Programmstart
 * + @author Nico
 * 
 * @version Revision 1 - MAIN Changes 
 * + Grundkonstrukt
 * + @author Erik
 */
public class Quiz {
	{
		// Set Look & Feel
		try {
			javax.swing.UIManager
					.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
			// javax.swing.UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
		} catch (Exception e) {
		}
	}
	
	//TODO Pfadanpassung!!
    private String pathToFiles = "data/"; // Path for release
	//private String pathToFiles = "src/wasweisichquiz/"; // Path to run in Eclipse
	private String loadedFilename;
	private Vector<Question> questions = new Vector<Question>();
	private Random random;
	private Question actualQuestion;
	private QuizGUI quizGui;
	private int countRichtig = 0, countFalsch = 0;
	private String filename = null;
        
	public Quiz() {

		boolean wiederhole = true;

		while(wiederhole) {
			
				String extFile = "Externe Datei laden...";
		
		
                List<String> fileList = new ArrayList<String>();
				try {
					//Search in directory for question files
					File f = new File(pathToFiles);
					File[] fileArray = f.listFiles();
					for (int i = 0; i < fileArray.length; i++) {
					    filename = fileArray[i].getName();
					    if(filename.indexOf(".qz") != -1){
					        fileList.add(fileArray[i].getName());
					    }
					}
				} catch (NullPointerException npe) {
					// No files found
				}

                
                String[] fileNames = new String[1+fileList.size()];
                fileNames[0] = extFile;
                for( int i = 1; i < fileNames.length; i++ )
                  fileNames[i] = fileList.get( i-1 ).toString();
            
                //show files in an dropdown box
                Object selectedValue = JOptionPane.showInputDialog(null,    
                    "Fragensatz ausw\u00E4hlen:", "Quizdatei laden",   
                    JOptionPane.INFORMATION_MESSAGE, null,
                    fileNames, fileNames[0]);
                
                //exit Programm on cancel
                if (selectedValue == null){
                    System.exit(0);
                }

                if (selectedValue.equals(extFile)) {
                	// load external file

                	// Create a file chooser -> Open file dialog
    				JFileChooser chooser = new JFileChooser();
    				chooser.setMultiSelectionEnabled(false); // one file only

    				chooser.addChoosableFileFilter(new FileFilter() {

    					@Override
    					public String getDescription() {
    						return "Fragendatei (*.qz)";
    					}

    					@Override
    					public boolean accept(File file) {
    						// Convert to lower case before checking extension
    						return (file.getName().toLowerCase().endsWith(".qz") || file
    								.isDirectory());
    					}
    				});

    				
    				int option = chooser.showOpenDialog(null);
    				if (option == JFileChooser.APPROVE_OPTION) {
    					File sf = chooser.getSelectedFile();
    					filename = sf.getAbsolutePath();
    					loadedFilename = sf.getName();
    					wiederhole = false;
    				} else {
    					// opening file was cancelled
    					wiederhole = true;
    				}
                	
                } else {
                	//get selected file
                	filename = pathToFiles + selectedValue.toString();
                	loadedFilename = selectedValue.toString();
                	wiederhole = false;
                }
                
		} // while
                
                
		random = new Random();

		try {
			questions = Question.deserializeQuestions(filename);
		} catch (FileNotFoundException e) {			
			JOptionPane.showMessageDialog(null, "Fragen-Datei konnte nicht gefunden werden.");
		}
		
		quizGui = new QuizGUI(this);
		actualQuestion = getNewQuestion();
		quizGui.loadQuestion(actualQuestion);
		
		quizGui.updateLabelNoch();
		
		quizGui.setLocationRelativeTo(null);
		quizGui.setVisible(true);
	}

	/**
	 * Laedt uebergebene Fragendatei (benutzt deserializeQuestions)
	 * zeigt diese aber nicht auf den Buttons an!
	 * 
	 * @param dateiName
	 * 
	 * @see reloadQuestionFilePart2
	 */
	void reloadQuestionFilePart1(String dateiName) {
		
		this.filename = dateiName;
		
		actualQuestion.resetQuestionAnswersToDefault();
		
		try {
			questions = Question.deserializeQuestions(filename);
		} catch (FileNotFoundException e) {			
			JOptionPane.showMessageDialog(null, "Fragen-Datei konnte nicht gefunden werden.");
		}
		
	}
	
	
	/**
	 * Laedt die eben mit reloadQuestionFilePart1 
	 * eingelesene Fragendatei auf die Buttons
	 * 
	 * @see reloadQuestionFilePart1
	 */
	void reloadQuestionFilePart2() {
		actualQuestion = getNewQuestion();
		quizGui.loadQuestion(actualQuestion);
	}
	
	/**
	 * Gibt eine neue Frage zurueck und entfernt diese aus der Liste
	 * 
	 * @return Question
	 */
	private Question getNewQuestion(){
		if(questions.size()<=0){
			
			quizGui.setQuestionCounterCaption("[ Keine Datei geladen ]");
			quizGui.updateLabelNoch();
			
			return new Question("<center><span style=\"background-color: #FFFF00\"> &nbsp; " +
					"<b><font color=#0000BB>Keine weitere Frage vorhanden. Lade eine neue Fragendatei. &nbsp;</font></b></span></center>");
		}
		// Fragen in zufaelliger Reihenfolge wiedergeben
		int index = random.nextInt(questions.size());
		Question returnQuestion = questions.get(index);
		questions.remove(index);
		return returnQuestion;
	}

	void nextQuestion(){
		actualQuestion = getNewQuestion();
		if(actualQuestion.getRightAnswer()==0){
			quizGui.disableAnswerButtons();
		}
		quizGui.loadQuestion(actualQuestion);
	}

	public boolean isRigthAnswer(int index){
		if(actualQuestion.getRightAnswer() == index)
			return true;
		return false;
	}

	int getRigthAnswer(){
		return actualQuestion.getRightAnswer();
	}
	
	public int getActualNumberOfQuestions(){
		return questions.size();
	}
	

	// --------------- GETTER and SETTER --------------- //
	
	public Question getActualQuestion() {
		return actualQuestion;
	}
	
	public String getPathToFiles() {
		return pathToFiles;
	}
	
	public String getLoadedFilename() {
		return loadedFilename;
	}

	public void setLoadedFilename(String dateiname) {
		this.loadedFilename = dateiname;
	}
	
	public int getCountRichtig() {
		return countRichtig;
	}
	
	public void setCountRichtig(int countRichtig) {
		this.countRichtig = countRichtig;
	}
	
	public int getCountFalsch() {
		return countFalsch;
	}
	
	public void setCountFalsch(int countFalsch) {
		this.countFalsch = countFalsch;
	}

}
